package com.rainkaze.IntelliDrawNote;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatDelegate;
import androidx.appcompat.widget.Toolbar;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.navigation.NavigationBarView;
import com.rainkaze.IntelliDrawNote.databinding.ActivityMainBinding;
import com.rainkaze.IntelliDrawNote.fragment.AiFragment;
import com.rainkaze.IntelliDrawNote.fragment.NoteListFragment;
import com.rainkaze.IntelliDrawNote.fragment.TodoListFragment;
import com.rainkaze.IntelliDrawNote.ui.NoteEditActivity;
import com.rainkaze.IntelliDrawNote.ui.TodoEditActivity;
import androidx.core.view.WindowInsetsCompat;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private ActivityMainBinding binding;
    // 添加一个变量来跟踪当前Fragment位置
    private int currentFragmentPosition = 0; // 0=Note, 1=AI, 2=待办
    private List<Fragment> list;
    private BottomNavigationView bottomNavigationView;

    private Toolbar toolbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        toolbar=binding.toolbar;
        setSupportActionBar(toolbar);
        getSupportActionBar().setTitle("笔记");

        binding.setIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showOptionsDialog();
            }
        });

        // 初始化 BottomNavigationView
        bottomNavigationView=binding.bottomNavigation;

        // 适配系统底部导航栏（兼容不同API级别），
        // TODO：不知道为啥直接relavant格式无效，导航栏底部会留白,所以写了这个
        View decorView = getWindow().getDecorView();
        decorView.setOnApplyWindowInsetsListener((v, insets) -> {
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
                WindowInsetsCompat windowInsetsCompat = WindowInsetsCompat.toWindowInsetsCompat(insets);
                int bottomInset = windowInsetsCompat.getInsets(WindowInsetsCompat.Type.systemBars()).bottom;
                bottomNavigationView.setPadding(0, 0, 0, bottomInset);
                return insets.consumeSystemWindowInsets();  // 返回处理过的 insets
            } else {
                bottomNavigationView.setPadding(0, 0, 0, 0);
                return insets;
            }
        });

        list = new ArrayList<>();
        list.add(new NoteListFragment());
        list.add(new AiFragment());
        list.add(new TodoListFragment());

        showFragment(list.get(0));

        // 底部导航栏的点击事件
        if (bottomNavigationView != null) {
            bottomNavigationView.setOnItemSelectedListener(new NavigationBarView.OnItemSelectedListener() {
                @Override
                public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                    if (item.getItemId() == R.id.menu_note) {
                        showFragment(list.get(0));
                        getSupportActionBar().setTitle("笔记");
                        binding.addIv.setVisibility(View.VISIBLE);
                        currentFragmentPosition = 0;
                    } else if (item.getItemId() == R.id.menu_ai) {
                        showFragment(list.get(1));
                        getSupportActionBar().setTitle("AI助记");
                        binding.addIv.setVisibility(View.GONE);
                        currentFragmentPosition = 1;
                    } else if (item.getItemId() == R.id.menu_todo) {
                        showFragment(list.get(2));
                        getSupportActionBar().setTitle("待办");
                        binding.addIv.setVisibility(View.VISIBLE);
                        currentFragmentPosition = 2;
                    }
                    return true;
                }
            });
        }
        // 设置状态栏和导航栏的Padding
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        // 添加点击事件，按钮在笔记和待办页面有着不同的功能
        binding.addIv.setOnClickListener(v -> {
            if (currentFragmentPosition == 0) {
                startActivityForResult(new Intent(MainActivity.this, NoteEditActivity.class), 100);
            } else if (currentFragmentPosition == 2) {
                startActivityForResult(new Intent(MainActivity.this, TodoEditActivity.class), 101);
            }
        });
        // 初始化并显示第一个Fragment
        NoteListFragment fragment = new NoteListFragment();
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.fragment_container, fragment);
        transaction.commit();

        // debug:调错
        Thread.setDefaultUncaughtExceptionHandler((thread, throwable) -> {
            throwable.printStackTrace();
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 100) {  // Note编辑返回
                NoteListFragment noteFragment = (NoteListFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_container);
                if (noteFragment != null) {
                    noteFragment.findAll();
                }
            } else if (requestCode == 101) {  // 待办编辑返回
                TodoListFragment todoFragment = (TodoListFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_container);
                if (todoFragment != null) {
                    todoFragment.findAll();
                }
            }
        }

    }

    private void showFragment(Fragment fragment) {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.replace(R.id.fragment_container, fragment);
        ft.commit();
    }

    // 设置界面样式的选项对话框
    //TODO：增设更多自定义主题，以及设置默认主题为日间模式
    private void showOptionsDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("选择操作");
        builder.setItems(new CharSequence[]{"日间模式", "夜间模式"}, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if(which == 0){
                    AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
                } else if(which == 1){
                    AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
                }
                recreate();
            }
        });
        builder.create().show();
    }
}